/*
 * Copyright (c) 2009, Servoy-stuff
 * 
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 * 
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 * http://www.fsf.org/licensing/licenses/lgpl.txt
 */

package net.stuff.servoy.beans.calendar.wicket;

import java.text.SimpleDateFormat;
import java.util.Locale;

import net.stuff.servoy.beans.calendar.IDateChooserBeanComponent;

import org.apache.wicket.Session;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.wicketstuff.calendar.util.DateConverter;

/**
 * 
 * @author servoy-stuff
 * http://www.servoy-stuff.net/
 */
public class MutablePatternDateConverter extends DateConverter {

	private static final long serialVersionUID = 1L;
	private SimpleDateFormat sdf;
	private String datePattern;
	private IDateChooserBeanComponent parent;
	
	public MutablePatternDateConverter(String datePattern, 
			boolean applyTimeZoneDifference, IDateChooserBeanComponent parent) {
		
		super(applyTimeZoneDifference);
	    if (datePattern == null)
	    	throw new IllegalArgumentException("datePattern must be not null");

	    setDatePattern(datePattern);
	    this.parent = parent;
	}
	
	/* (non-Javadoc)
	 * @see org.wicketstuff.calendar.util.DateConverter#convertToObject(java.lang.String, java.util.Locale)
	 */
	@Override
	public Object convertToObject(String value, Locale locale) {
		if (value != null) {
			if (!parent.getValidationEnabled()) {
				return value;
			}
			try {
				sdf.setLenient(false);
				sdf.parse(value);
				return super.convertToObject(value, locale);
			} catch (Exception ex) {
				return value;
			}
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see org.wicketstuff.calendar.util.DateConverter#getDatePattern()
	 */
	public String getDatePattern() {
		return datePattern;
	}
	
	public void setDatePattern(String datePattern) {
		if (datePattern != null) {
			this.datePattern = datePattern;
			this.sdf = new SimpleDateFormat(datePattern);
		}
	}

	/* (non-Javadoc)
	 * @see org.wicketstuff.calendar.util.DateConverter#getFormat()
	 */
	public DateTimeFormatter getFormat() {
		return DateTimeFormat.forPattern(this.datePattern).withLocale(
				Session.get().getLocale());
	}

}
